#include <iostream>
#include <sys/ipc.h>    // Inter-Process Communication
#include <sys/msg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string>
#include <cstring>

const std::string pathname = "/home/LHY/test/messageQueue";
const int proj_id = 0x11223344;

const std::string filename = ".fifo";

#define MAX_TEXT 512    // 消息块大小

#define ATYPE 1
#define BTYPE 2

key_t GetKey()
{
    key_t key = ftok(pathname.c_str(), proj_id);
    // 判断是否ftok成功
    if (key < 0)
    {
        std::cerr << "errno: " << errno << ", errstring" << strerror(errno) << std::endl;
        exit(1);
    }
    return key;
}

// 消息块
struct msg_buffer 
{
    long msg_type;
    char msg_text[MAX_TEXT];
};

int createMessageQueueHelper(key_t key, int flag)
{
    int msg_id = msgget(key, flag);
    if (msg_id == -1) 
    {
        std::cerr << "Message queue not created" << std::endl;
        return -1;
    }
    return msg_id;
}

int createMessageQueue(key_t key) 
{
    return createMessageQueueHelper(key, IPC_CREAT | IPC_EXCL | 0666);
}

int getMessageQueue(key_t key)
{
    return createMessageQueueHelper(key, IPC_CREAT);
}

bool sendMessage(int queue_id, long type, const char* text) 
{
    struct msg_buffer message;
    message.msg_type = type;
    strncpy(message.msg_text, text, MAX_TEXT);

    if (msgsnd(queue_id, &message, sizeof(message) - sizeof(long), 0) == -1) 
    {
        std::cerr << "Message send failed" << std::endl;
        return false;
    }
    return true;
}

bool receiveMessage(int queue_id, long type, char* buffer) 
{
    struct msg_buffer message;
    message.msg_type = type;

    if (msgrcv(queue_id, &message, sizeof(message) - sizeof(long), type, 0) == -1) 
    {
        std::cerr << "Message receive failed" << std::endl;
        return false;
    }

    strncpy(buffer, message.msg_text, MAX_TEXT);
    return true;
}

bool MakeFifo()
{
    int n = mkfifo(filename.c_str(), 0666);
    if (n < 0)
    {
        std::cerr << "errno: " << errno << ", errstring: " << strerror(errno) << std::endl;
        return false;
    }

    std::cout << "mkfifo success... read" << std::endl;
    return true;
}